import time

from scp import SCPClient
import paramiko
from tqdm import tqdm


def upload_file_to_linux_scp(local_path, remote_path, hostname, username, password=None, port=22, key_filepath=None):
    """
    使用SCP协议上传文件到Linux服务器

    参数同SFTP版本
    """
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        if key_filepath:
            private_key = paramiko.RSAKey.from_private_key_file(key_filepath)
            ssh.connect(hostname=hostname, port=port, username=username, pkey=private_key)
        else:
            ssh.connect(hostname=hostname, port=port, username=username, password=password)

        # 使用SCP客户端
        with SCPClient(ssh.get_transport(), progress=progress) as scp:
            scp.put(local_path, remote_path)

        print(f"文件上传成功: {local_path} -> {hostname}:{remote_path}")

    except Exception as e:
        print(f"上传失败: {str(e)}")
    finally:
        ssh.close()


last_update = 0
update_interval = 1  # 秒


def progress(filename, size, sent):
    global last_update
    now = time.time()
    if now - last_update >= update_interval:
        print(f"{filename}: {sent / size:.1%}")
        last_update = now


if __name__ == "__main__":
    upload_file_to_linux_scp(
        local_path="D:\家宽\告警\hw\华为所有告警信息0714\hw20250714.zip",
        remote_path="/hddisk/data_backup/告警/hw20250714.zip",
        hostname="192.168.67.56",
        username="root",
        password="wxxx2jiakuan"
    )
